package Client.Dropbox.Communication

import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote.Node
import scala.actors.remote.RemoteActor._
import objects._
import Client.Dropbox.Manager.FileManager

/**
 * Remote Actor for the client to send messages to the server
 * @param port the port with which the Communicator connects to the server
 * @param peer the server
 */
class Communicator (port: Int, peer: Node) extends Actor {
  /**
   * The action method for the Communicator Actor
   */
  def act {
    //initialize remote actor and create contact with actors on server
    alive(port) 
    register('Client, self)
	val newFile = select(peer, 'NewFile)
	val changedFile = select(peer, 'ChangedFile)
	val uploadFile = select(peer, 'UploadFile)
	val deletedFile = select(peer, 'DeletedFile)
	val newFolder = select(peer, 'NewFolder)
	val deletedFolder = select(peer, 'DeletedFolder)
	//receive messages from operating system and send them to server
    loop {
      react {
        case ("newFile", f:File2) => newFile ! (f.uid, f.cid, f.name, f.parent, f.size, f.code)
        case ("changedFile", f:File2) => changedFile ! (f.uid, f.cid, f.name, f.parent, f.size, f.code)
        case ("upload", f:File3) => uploadFile ! (f.uid, f.cid, f.name, f.parent, f.size, f.code, f.bytes)
        case ("deletedFile", f:File1) => deletedFile ! (f.uid, f.cid, f.name, f.parent)
        //if a new folder was created, enter it into the hash map at FileManager
        case ("newFolder", name:String, f:File1) => {
          println("sending new folder...........")
          var id=(newFolder !? (f.uid, f.cid, f.name, f.parent)).asInstanceOf[Long]
          println("Added new folder.  Name: "+name+"ID: "+id)
          FileManager.add(name, id)
        }
        case ("deletedFolder", f:File1) => deletedFolder ! (f.uid, f.cid, f.name, f.parent)
        case "stop" => exit
      }
    }
  }
}